from django.utils import timezone

from django.db import models

class Permission(models.Model):
    name = models.CharField(max_length=255)
    code = models.CharField(max_length=255, unique=True)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.name


class Role(models.Model):
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(blank=True, null=True)
    permissions = models.ManyToManyField(Permission, blank=True)
    functions = models.TextField(blank=True, null=True)  # 新增字段，存储功能名称，逗号分隔

    def __str__(self):
        return self.name


class User(models.Model):
    username = models.CharField(max_length=50, unique=True)
    password_hash = models.CharField(max_length=255)
    email = models.EmailField(max_length=100, blank=True, null=True)
    phone_number = models.CharField(max_length=15, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    ROLE_CHOICES = [
        ('admin', '管理员'),
        ('super_admin', '超级管理员'),
        ('user', '普通用户'),
    ]
    role_name = models.CharField(max_length=20, choices=ROLE_CHOICES, default='user')
    mg_state = models.BooleanField(default=False)
    role_description = models.CharField(max_length=255, blank=True, null=True, verbose_name='角色描述', default='普通用户')
    permissions = models.ManyToManyField(Permission, blank=True)

    def __str__(self):
        return self.username


class Category(models.Model):
    name = models.CharField(max_length=255)
    parent_category = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='subcategories')
    description = models.TextField(blank=True, null=True)
    STATUS_CHOICES = [
        ('enabled', 'Enabled'),
        ('disabled', 'Disabled'),
    ]
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='enabled')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class Product(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.IntegerField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='products/', blank=True, null=True)
    STATUS_CHOICES = [
        ('published', 'Published'),
        ('unpublished', 'Unpublished'),
    ]
    status = models.CharField(max_length=12, choices=STATUS_CHOICES, default='published')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class CategoryParameter(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='parameters')
    name = models.CharField(max_length=255)
    VALUE_TYPE_CHOICES = [
        ('text', 'Text'),
        ('number', 'Number'),
        ('boolean', 'Boolean'),
    ]
    value_type = models.CharField(max_length=10, choices=VALUE_TYPE_CHOICES, default='text')
    default_value = models.CharField(max_length=255, blank=True, null=True)
    required = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.category.name} - {self.name}"


class Order(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    total_price = models.DecimalField(max_digits=10, decimal_places=2)
    STATUS_CHOICES = [
        ('Pending', 'Pending'),
        ('Completed', 'Completed'),
        ('Cancelled', 'Cancelled'),
    ]
    status = models.CharField(max_length=9, choices=STATUS_CHOICES, default='Pending')
    created_at = models.DateTimeField(auto_now_add=True)
    pay_status = models.CharField(max_length=20, blank=True, null=True)
    is_send = models.BooleanField(default=False)
    fapiao_title = models.CharField(max_length=50, choices=[('个人', '个人'), ('公司', '公司')], blank=True, null=True)
    fapiao_company = models.CharField(max_length=255, blank=True, null=True)
    fapiao_content = models.CharField(max_length=255, blank=True, null=True)
    consignee_addr = models.TextField(blank=True, null=True)
    payment_method = models.CharField(max_length=50, blank=True, null=True)  # 支付方式
    shipping_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0)  # 运费
    total_amount = models.DecimalField(max_digits=10, decimal_places=2)  # 订单总金额（含运费）
    consignee_name = models.CharField(max_length=50)  # 收货人姓名
    consignee_tel = models.CharField(max_length=15)  # 收货人电话
    consign_time = models.DateTimeField(null=True, blank=True)  # 发货时间

    def __str__(self):
        return f"Order {self.id} by {self.user.username}"


class OrderDetail(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    price_at_time_of_purchase = models.DecimalField(max_digits=10, decimal_places=2)

    def __str__(self):
        return f"OrderDetail for Order {self.order.id}, Product {self.product.name}"


class Banner(models.Model):
    imgUrl = models.CharField(max_length=255)
    hrefUrl = models.CharField(max_length=255, default='/')
    type = models.IntegerField(choices=[
        (1, '页面'),
        (2, 'H5'),
        (3, '小程序')
    ])
    distributionSite = models.IntegerField(choices=[
        (1, '首页'),
        (2, '分类商品页')
    ], default=1)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"Banner at {self.get_distributionSite_display()}"

    class Meta:
        ordering = ['created_at']


class CartItem(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    selected = models.BooleanField(default=True)
    count = models.IntegerField(default=1)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('user', 'product')

    def __str__(self):
        return f"{self.user.username}'s cart - {self.product.name}"



    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.parent.name} - {self.name}"

    class Meta:
        ordering = ['created_at']



    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.parent.name} - {self.name}"

    class Meta:
        ordering = ['created_at']



    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.parent.name} - {self.name}"

    class Meta:
        ordering = ['created_at']



    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.parent.name} - {self.name}"

    class Meta:
        ordering = ['created_at']



    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.parent.name} - {self.name}"

    class Meta:
        ordering = ['created_at']



    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.parent.name} - {self.name}"

    class Meta:
        ordering = ['created_at']



    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.parent.name} - {self.name}"

    class Meta:
        ordering = ['created_at']



    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.parent.name} - {self.name}"

    class Meta:
        ordering = ['created_at']


class CategoryHead(models.Model):
    name = models.CharField(max_length=50, verbose_name='分类名称')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class CategoryHeadChild(models.Model):
    parent = models.ForeignKey(CategoryHead, on_delete=models.CASCADE, related_name='children')
    name = models.CharField(max_length=50, verbose_name='子分类名称')
    picture = models.URLField(verbose_name='子分类图片')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.parent.name} - {self.name}"

    class Meta:
        ordering = ['created_at']


class CategoryHead(models.Model):
    name = models.CharField(max_length=50, verbose_name='分类名称')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class CategoryHeadChild(models.Model):
    parent = models.ForeignKey(CategoryHead, on_delete=models.CASCADE, related_name='children')
    name = models.CharField(max_length=50, verbose_name='子分类名称')
    picture = models.URLField(verbose_name='子分类图片')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.parent.name} - {self.name}"

    class Meta:
        ordering = ['created_at']


class CategoryHead(models.Model):
    name = models.CharField(max_length=50, verbose_name='分类名称')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class CategoryHeadChild(models.Model):
    parent = models.ForeignKey(CategoryHead, on_delete=models.CASCADE, related_name='children')
    name = models.CharField(max_length=50, verbose_name='子分类名称')
    picture = models.URLField(verbose_name='子分类图片')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.parent.name} - {self.name}"

    class Meta:
        ordering = ['created_at']


class CategoryHead(models.Model):
    name = models.CharField(max_length=50, verbose_name='分类名称')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class CategoryHeadChild(models.Model):
    parent = models.ForeignKey(CategoryHead, on_delete=models.CASCADE, related_name='children')
    name = models.CharField(max_length=50, verbose_name='子分类名称')
    picture = models.URLField(verbose_name='子分类图片')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.parent.name} - {self.name}"

    class Meta:
        ordering = ['created_at']